using System;
using System.ServiceModel;

namespace SeguradoraIA.Framework.Service
{
    public class ProxyFactory<T> : IDisposable where T : class
    {
        private ChannelFactory<T> factory;

        public ProxyFactory()
        {
            var endpointName = typeof(T).FullName;
            factory = new ChannelFactory<T>(endpointName);
        }

        #region IDisposable Members

        public void Dispose()
        {
            Close();
        }

        #endregion

        public T Create()
        {
            return factory.CreateChannel();
        }

        public void Close()
        {
            try
            {
                if (factory.State == CommunicationState.Faulted)
                {
                    factory.Abort();
                }

                if (factory.State != CommunicationState.Closed)
                {
                    factory.Close();
                }
            }
            finally
            {
                if (factory.State == CommunicationState.Faulted)
                {
                    factory.Abort();
                }
            }
        }
    }
}